package com.shujia.redis;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RedisApi {

    Jedis jedis;

    @Before
    public void init() {
        //1、创建连接
        jedis = new Jedis("master", 7000);

        //指定密码
//        jedis.auth("123456");
    }


    @Test
    public void lpush() {
        jedis.lpush("l3", "java");
    }


    @Test
    public void blpop() {
        /**
         * blpop ；阻塞等待数据，只要列表中有数据就会取走，需要指定一个超时时间
         * 如果时间指定为0,就是一直等
         *
         */
        while (true) {
            List<String> l2 = jedis.blpop(0, "l2");

            System.out.println(l2);
        }

    }


    @Test
    public void hset() {
        //一次存一条
        jedis.hset("h3", "id", "003");


        //一次存多条
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("name", "王五");
        hashMap.put("age", "25");
        jedis.hmset("h3", hashMap);
    }


    @Test
    public void hget() {
        //取一个列
        String id = jedis.hget("h3", "id");
        System.out.println(id);

        //取所有列
        Map<String, String> map = jedis.hgetAll("h3");
        System.out.println(map);

    }


    @Test
    public void student() throws Exception {




        FileReader fileReader = new FileReader("data/students.txt");

        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String line;

        while ((line = bufferedReader.readLine()) != null) {

            String id = "student:" + line.split(",")[0];

            String[] split = line.split(",");


            String name = split[1];
            String age = split[2];
            String gender = split[3];
            String clazz = split[4];


            HashMap<String, String> hashMap = new HashMap<>();

            hashMap.put("name", name);
            hashMap.put("age", age);
            hashMap.put("gender", gender);
            hashMap.put("clazz", clazz);

            jedis.hmset(id, hashMap);
        }
    }


}
